<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/4
 * Time: 13:18
 */

namespace common\business\mdmtask;


use common\business\DbHandler;
use common\business\mdm\MdmApiHandler;
use common\consts\CommonResources;
use common\consts\Consts;
use common\consts\MdmConsts;
use common\models\MdmTask;
use common\result\ActionResult;
use Yii;
use yii\helpers\Json;

class MdmTaskService extends DbHandler
{
    private $_MAX_PER_TIME = 20;
    /**
     * @var integer
     */
    protected $_mdm_task_id;
    public function setMdmTaskId($mdm_task_id){
        $this->_mdm_task_id = $mdm_task_id;
    }

    /**
     * @var integer
     */
    protected $_totalCount;

    /**
     * @param callback|null $writeBackHandler
     * @return ActionResult
     */
    public function execute($writeBackHandler = null){
        $totalResult = new ActionResult();

        if ($this->_mdm_task_id){
            $this->_totalCount = 1;
            $this->findAndExecuteSingle($this->_mdm_task_id, $totalResult, $writeBackHandler);
            return $totalResult;
        }
        $query = MdmTask::find()
            ->select(['id'])
            ->andFilterWhere(['flag' => [Consts::MDM_TASK_FLAG_INIT, Consts::MDM_TASK_FLAG_FAIL]]);
        $totalCount = $query->count();
        if ($totalCount > $this->_MAX_PER_TIME){
            $this->_totalCount  = $this->_MAX_PER_TIME;
            $mdmTask_arr = $query->orderBy(['updated_at' => SORT_DESC])->limit($this->_MAX_PER_TIME)->all();
        }
        else {
            $mdmTask_arr = $query->orderBy(['updated_at' => SORT_DESC])->all();
            $this->_totalCount = sizeof($mdmTask_arr);
        }

        if ($this->_totalCount == 0){
            $totalResult->isSkipped = true;
            return $totalResult;
        }

        foreach ($mdmTask_arr as $mdmTask){
            $this->findAndExecuteSingle($mdmTask['id'], $totalResult, $writeBackHandler);
        }
        return $totalResult;
    }

    /**
     * @param string $mdm_id
     * @param ActionResult $totalResult
     * @param callback|null $writeBackHandler
     * @return boolean
     */
    protected function findAndExecuteSingle($mdm_id, $totalResult, $writeBackHandler = null){
        $action = Yii::t('app', 'execute');
        $modelClass = Yii::t('app', MdmTask::className());

        $intId = intval($mdm_id);
        $mdmTask = MdmTask::findOne($intId);
        if (!$mdmTask){
            $totalResult->addSubResult(new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG($action, $modelClass), true));
            $this->executeWriteBackHandlerWithTotal($totalResult,$this->_totalCount,$writeBackHandler);
            return false;
        }

        $totalResult->addSubResult($this->executeSingle($mdmTask));
        $this->executeWriteBackHandlerWithTotal($totalResult,$this->_totalCount,$writeBackHandler);
        return true;
    }

    /**
     * @param MdmTask $mdm_task
     * @return ActionResult
     */
    protected function executeSingle($mdm_task){
        $action = Yii::t('app', 'execute single');
        $modelClass = Yii::t('app', MdmTask::className());

        $api = new MdmTaskApiHandler();

//        $mdm_task->flag = Consts::MDM_TASK_FLAG_RUNNING;
//        $api->updateMdmTask($mdm_task);

        $webService = new MdmApiHandler();
        $resultStr = $webService->webServiceCallSync($mdm_task->input);
        $resultArr = Json::decode($resultStr);
        $mdm_task->flag = $resultArr[MdmConsts::RESULT] == '1' ? Consts::MDM_TASK_FLAG_SUCCESS : Consts::MDM_TASK_FLAG_FAIL;
        $mdm_task->output = $resultStr;
        $api->updateMdmTask($mdm_task);

        return new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG_DETAIL($action, $modelClass, $resultStr));
    }
}